<template>
  <div class="container">
    <div v-show="isEndStatus" style="display:flex" :style="{ color }">
      <div>{{obj.dd}}</div>
      <div>天</div>
      <div>{{obj.hh}}</div>
      <div>时</div>
      <div>{{obj.mm}}</div>
      <div>分</div>
      <div>{{obj.ss}}</div>
      <div>秒</div>
    </div>
  </div>
</template>
<script>
export default {
  name: "data-v-count-down",
  props: {
    // 结束的时间毫秒数
    endTime: {
      type: Number,
      default: Date.now() + 10000,
    },
    // 显示倒计时格式
    formatter: {
      type: String,
      default: "dd-hh-mm-ss",
    },
    // 字体颜色
    color: {
      type: String,
      default: "rgba(255,255,255,0.5)",
    },
  },
  data() {
    return {
      countDownItem: "",
      newTime: null,
      // 倒计时是否执行完毕
      isEndStatus: true,
      obj: {
        dd: "00",
        hh: "00",
        mm: "00",
        ss: "00",
      },
    };
  },
  methods: {
    timeFormat(param) {
      return param < 10 ? "0" + param : param;
    },
    countDown() {
      const interval = setInterval(() => {
        const newTime = new Date().getTime();
        const endTime = new Date(this.endTime + 2000).getTime();
        let obj = null;
        if (endTime - newTime > 0) {
          const time = (endTime - newTime) / 1000;
          const day = parseInt(time / (60 * 60 * 24));
          const hou = parseInt((time % (60 * 60 * 24)) / 3600);
          const min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
          const sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
          obj = {
            dd: this.timeFormat(day),
            hh: this.timeFormat(hou),
            mm: this.timeFormat(min),
            ss: this.timeFormat(sec),
          };
          if (this.newTime) {
            this.$emit("start-click", this.newTime);
          }
        } else {
          // 倒计时结束
          obj = {
            dd: "00",
            hh: "00",
            mm: "00",
            ss: "00",
          };
          this.isEndStatus = false;
          clearInterval(interval);
          this.$emit("end-click", this.countDownItem);
        }
        const timeList = this.formatter.split("-");
        // const dateList = ["天", "时", "分", "秒"];
        // 循环判断如果用户传过来的日期，包含对象中的属性，那么就使用该属性的值
        let newObj = {};
        Object.keys(obj).forEach((key) => {
          if (timeList.includes(key)) {
            newObj[key] = obj[key];
          }
        });
        this.obj = newObj;
      }, 1000);
    },
  },
  mounted() {
    this.countDown();
  },
};
</script>
